package net.soevar.common;

import java.util.ArrayList;
import java.util.Collection;

import net.soevar.database.model.AthRole;
import net.soevar.database.model.AthUser;
import net.soevar.database.model.Jobseeker;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zkoss.zkplus.hibernate.HibernateUtil;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		Session session = HibernateUtil.getSessionFactory().openSession();
		AthUser users = (AthUser) session.createCriteria(AthUser.class)
				.add(Restrictions.eq("userId", username))
				.add(Restrictions.eq("statusAktif", true))
				.add(Restrictions.eq("statusApproval", true)).setMaxResults(1)
				.uniqueResult();

		Jobseeker jobseeker = null;
		if (users == null) {
			jobseeker = (Jobseeker) session.createCriteria(Jobseeker.class)
					.add(Restrictions.eq("jobseekerId", username))
					.add(Restrictions.eq("statusAktif", true))
					.add(Restrictions.eq("statusApproval", true))
					.setMaxResults(1).uniqueResult();
			// System.out.println("user not found: " + users);
		}

		System.out.println("username = " + username + " users = " + users);

		session.close();
		if (users == null && jobseeker == null) {
			throw new UsernameNotFoundException("user not found");
		} else if (users != null) {

			String password = null;
			try {
				password = Common.desEncrypter.decrypt(users.getUserPassword()
						.trim());
				// System.out.println("password = " + password);
			} catch (Exception e) {
				e.printStackTrace();
			}
			boolean enabled = true;
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;

			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			AthRole role = users.getUserRole();
			if (role != null) {
				authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
			}

			if (users != null && users.getStatusRoot() != null
					&& users.getStatusRoot()) {
				authorities.add(new GrantedAuthorityImpl("ROLE_SUPERVISOR"));
			}

			User user = new User(username, password, enabled,
					accountNonExpired, credentialsNonExpired, accountNonLocked,
					authorities);
			return user;
		}

		else {
			String password = null;
			try {
				password = Common.desEncrypter.decrypt(jobseeker
						.getJobseekerPassword().trim());
				// System.out.println("password = " + password);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			boolean enabled = true;
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;

			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

			authorities.add(new GrantedAuthorityImpl("ROLE_USER"));

			User user = new User(username, password, enabled,
					accountNonExpired, credentialsNonExpired, accountNonLocked,
					authorities);
			return user;
		}

	}
}